virtualenv.py 3.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119
  1. from __future__ import absolute_import
  2. import io
  3. import logging
  4. import os
  5. import re
  6. import site
  7. import sys
  8. from pip._internal.utils.typing import MYPY_CHECK_RUNNING
  9. if MYPY_CHECK_RUNNING:
  10. from typing import List, Optional
  11. logger = logging.getLogger(__name__)
  12. _INCLUDE_SYSTEM_SITE_PACKAGES_REGEX = re.compile(
  13. r"include-system-site-packages\s*=\s*(?P<value>true|false)"
  14. )
  15. def _running_under_venv():
  16. # type: () -> bool
  17. """Checks if sys.base_prefix and sys.prefix match.
  18. This handles PEP 405 compliant virtual environments.
  19. """
  20. return sys.prefix != getattr(sys, "base_prefix", sys.prefix)
  21. def _running_under_regular_virtualenv():
  22. # type: () -> bool
  23. """Checks if sys.real_prefix is set.
  24. This handles virtual environments created with pypa's virtualenv.
  25. """
  26. # pypa/virtualenv case
  27. return hasattr(sys, 'real_prefix')
  28. def running_under_virtualenv():
  29. # type: () -> bool
  30. """Return True if we're running inside a virtualenv, False otherwise.
  31. """
  32. return _running_under_venv() or _running_under_regular_virtualenv()
  33. def _get_pyvenv_cfg_lines():
  34. # type: () -> Optional[List[str]]
  35. """Reads {sys.prefix}/pyvenv.cfg and returns its contents as list of lines
  36. Returns None, if it could not read/access the file.
  37. """
  38. pyvenv_cfg_file = os.path.join(sys.prefix, 'pyvenv.cfg')
  39. try:
  40. # Although PEP 405 does not specify, the built-in venv module always
  41. # writes with UTF-8. (pypa/pip#8717)
  42. with io.open(pyvenv_cfg_file, encoding='utf-8') as f:
  43. return f.read().splitlines() # avoids trailing newlines
  44. except IOError:
  45. return None
  46. def _no_global_under_venv():
  47. # type: () -> bool
  48. """Check `{sys.prefix}/pyvenv.cfg` for system site-packages inclusion
  49. PEP 405 specifies that when system site-packages are not supposed to be
  50. visible from a virtual environment, `pyvenv.cfg` must contain the following
  51. line:
  52. include-system-site-packages = false
  53. Additionally, log a warning if accessing the file fails.
  54. """
  55. cfg_lines = _get_pyvenv_cfg_lines()
  56. if cfg_lines is None:
  57. # We're not in a "sane" venv, so assume there is no system
  58. # site-packages access (since that's PEP 405's default state).
  59. logger.warning(
  60. "Could not access 'pyvenv.cfg' despite a virtual environment "
  61. "being active. Assuming global site-packages is not accessible "
  62. "in this environment."
  63. )
  64. return True
  65. for line in cfg_lines:
  66. match = _INCLUDE_SYSTEM_SITE_PACKAGES_REGEX.match(line)
  67. if match is not None and match.group('value') == 'false':
  68. return True
  69. return False
  70. def _no_global_under_regular_virtualenv():
  71. # type: () -> bool
  72. """Check if "no-global-site-packages.txt" exists beside site.py
  73. This mirrors logic in pypa/virtualenv for determining whether system
  74. site-packages are visible in the virtual environment.
  75. """
  76. site_mod_dir = os.path.dirname(os.path.abspath(site.__file__))
  77. no_global_site_packages_file = os.path.join(
  78. site_mod_dir, 'no-global-site-packages.txt',
  79. )
  80. return os.path.exists(no_global_site_packages_file)
  81. def virtualenv_no_global():
  82. # type: () -> bool
  83. """Returns a boolean, whether running in venv with no system site-packages.
  84. """
  85. # PEP 405 compliance needs to be checked first since virtualenv >=20 would
  86. # return True for both checks, but is only able to use the PEP 405 config.
  87. if _running_under_venv():
  88. return _no_global_under_venv()
  89. if _running_under_regular_virtualenv():
  90. return _no_global_under_regular_virtualenv()
  91. return False